'''
author: Aeen
'''

import csv
import time
from urllib import request
from urllib import parse
import random
import requests


class Picture(object):

    def __init__(self):
        self.pathfile = r"I:\图片\stock_jianyue.csv"
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
            'Host': 'img.alicdn.com'
            }

    def get_url(self):
        '''just get url from csv'''
        with open(self.pathfile, 'r', newline='', encoding='gbk') as f:
            csv_reader = csv.DictReader(f)
            for one in csv_reader:
                yield (one['img'], one['item_id'])

    def get_picture(self, img_url, item_id):
        '''get one picture from one url and rename it'''
        print('宝贝', item_id, '开始下载')
        filename = 'I:\\图片\\{}.jpg'.format(item_id)
        # http_handler = request.HTTPHandler()
        # opener = request.build_opener(http_handler)
        try:
            # prequest = request.Request(img_url, self.headers)
            # picture_res = opener.open(prequest)
            # print(picture_res.read().decode('utf-8'))
            picture_res = requests.get(img_url, headers=self.headers, timeout=5).content
            # print(picture_res)
            with open(filename, 'wb') as fp:
                fp.write(picture_res)
            print('宝贝', item_id, '下载完成\n')
            time.sleep(3 + random.random())
        except IndexError as e:
            print(e)
        # return item_id, 'completed'

    def main(self):
        for i in self.get_url():
            try:
                img_url, item_id = i
                self.get_picture(img_url, item_id)
            except StopIteration as e:
                print(e)


if __name__ == '__main__':
    p = Picture()
    print(p.main())